package edu.tjpu.share.task;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.service.DownloadService;

public class DownloadTask extends
		AsyncTask<HashMap<String, Object>, Integer, HashMap<String, Object>> {

	String localfile = null;
	private int notification_id;
	private String filename;
	private String fileurl;
	private String storeurl;

	@Override
	protected HashMap<String, Object> doInBackground(
			HashMap<String, Object>... maps) {

		Handler mDownloadThreadHandler = (Handler) maps[0]
				.get("mDownloadThreadHandler");
		Handler downloadHandler = (Handler) maps[0].get("downloadHandler");
		filename = (String) maps[0].get(Fields.FILE_NAME);
		fileurl = (String) maps[0].get(Fields.FILE_URL);
		storeurl = (String) maps[0].get(Fields.STORE_URL);
		Server serverinfo = (Server) maps[0].get(Fields.SERVER_INFO);
		notification_id = (Integer) maps[0].get("notification_id");

		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append(fileurl);

		fileurl = sbhost.toString();
		fileurl = fileurl.replace('\\', '/');

		boolean status = false;

		if (avaiableMedia()) {
			AndroidHttpClient client = AndroidHttpClient
					.newInstance(Fields.USER_AGENT);

			try {

				// 创建 HttpGet 方法，该方法会自动处理 URL 地址的重定向
				HttpGet httpGet = new HttpGet(fileurl);

				// 请求HttpClient，取得HttpResponse
				HttpResponse httpResponse = client.execute(httpGet);

				// 请求成功
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity httpEntity = httpResponse.getEntity();

					// pd.setMax(Long.valueOf(httpEntity.getContentLength()).intValue());
					int count = 0;
					int totalSize = Long.valueOf(httpEntity.getContentLength())
							.intValue();
					InputStream is = httpEntity.getContent();

					FileOutputStream fileOutputStream = null;

					if (is != null) {
						File file = new File(createDir(storeurl), filename);
						fileOutputStream = new FileOutputStream(file);
						int ch = -1;
						int downloadPercent = 0;
						while ((ch = is.read()) != -1) {
							fileOutputStream.write(ch);
							count++;
							// pd.setProgress(count);
							if (((100 * count / totalSize) - 1) > downloadPercent) {
								downloadPercent++;
								Message msg = new Message();
								Bundle bundle = new Bundle();
								bundle.putString("filename", filename);
								bundle.putInt("notification_id",
										notification_id);
								bundle.putInt("downloadPercent",
										downloadPercent);
								msg.what = DownloadService.UPDATE_DOWNLOAD_PERCENT;
								msg.setData(bundle);
								downloadHandler.sendMessage(msg);
							}
						}

						if (count == totalSize) {
							status = true;
						} else {
							status = false;
						}
						localfile = Environment.getExternalStorageDirectory()
								+ "/share" + storeurl;
					}
					fileOutputStream.flush();

				} else {
					localfile = null;
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭连接
				client.close();
			}
		}
		HashMap<String, Object> outmap = new HashMap<String, Object>();
		outmap.put(Fields.HANDLER, mDownloadThreadHandler);
		outmap.put("downloadHandler", downloadHandler);
		outmap.put(Fields.STATUS, status);
		return outmap;
	}

	@Override
	protected void onPostExecute(HashMap<String, Object> result) {
		super.onPostExecute(result);
		if (isCancelled()) {
			result = null;
		}
		if (result != null) {
			Handler mDownloadThreadHandler = (Handler) result
					.get(Fields.HANDLER);
			if (localfile != null) {

				Handler downloadHandler = (Handler) result
						.get("downloadHandler");
				boolean status = (Boolean) result.get(Fields.STATUS);
				Message msg = downloadHandler.obtainMessage();
				Bundle bundle = new Bundle();
				bundle.putString("filename", filename);
				bundle.putInt("notification_id", notification_id);
				bundle.putString(Fields.FILE_URL, localfile);
				msg.setData(bundle);

				// String realFileName = filename;
				if (filename.length() > 9) {
					filename = filename.substring(0, 9)
							+ "..."
							+ filename.substring(filename.length() - 4,
									filename.length());
				}
				if (status) {
					msg.what = DownloadService.DOWNLOAD_COMPLETE;
				} else {
					msg.what = DownloadService.DOWNLOAD_FAILED;
				}
				downloadHandler.sendMessage(msg);
				mDownloadThreadHandler
						.sendEmptyMessage(DownloadService.DOWNLOAD_COMPLETE);
			}
		}
	}

	private static File createDir(String dirName) {
		File dir = new File(Environment.getExternalStorageDirectory()
				+ "/share" + dirName);
		dir.mkdirs();
		return dir;
	}

	// 判断是否有SD卡, ture:有SD卡, false:没有SD卡
	private static boolean avaiableMedia() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

}